<?php
/**
 * 系统配置
 * User: cxm
 * Date: 2019/10/24
 * Time: 17:39
 */
namespace App\Http\Controllers\Admin\System;
use App\Http\Controllers\Admin\Controller;
use App\Models\Config;
use App\Models\SystemConfig;
use DB,Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class ConfigController extends Controller {
    /**
     * 获取配置信息
     * URL GET:/admin/system/config
     * @param Request $request
     * @param string group_code 分组码
     * @return mixed
     */
    public function getConfig(Request $request){
        $params = $request->only(['group_code']);
        if (!array_key_exists('group_code',$params)) {
            return $this->error('缺少分组码');
        }
        // 基本配置
        $data = SystemConfig::getGroupCodeData($params['group_code']);
        return $this->success('操作成功',$data);
    }

    /**
     * 保存文件
     * URL POST:/admin/system/config/saveFile
     * @param Request $request
     * @param string group_code 分组码
     * @return mixed
     */
    public function saveFile(Request $request){
        $params = $request->only(['group_code']);
        if (!array_key_exists('group_code',$params)) {
            return $this->error('缺少分组码');
        }
        // 基本配置
        $data = SystemConfig::getGroupCodeDataSaveFile($params['group_code']);
        return $this->success('操作成功');
    }

    /**
     * 保存信息
     * URL POST:/admin/system/config/store
     * @param Request $request
     * @param array data [["key"=>"val"]]
     * @return array
     */
    public function store(Request $request)
    {
        $data = $request->only('data');
        $params = json_decode($data['data'],true);
        $i    = 0;
        foreach ($params as $key => $value) {
            $args[$i]['code'] = trim($key);
            $args[$i]['val']  = trim($value);
            $i++;
        }

        if (is_array($args)) {
            foreach ($args as $config) {
                SystemConfig::where('code', $config["code"])->update([
                    'val' => $config["val"]
                ]);
            }
        }
        SystemConfig::resetConfig();
        return $this->success('操作成功');
    }

    /**
     * 清除redis
     * URL POST:/admin/system/config/flush
     * @return mixed
     */
    public function flush(){
        Redis::flushall();
        return $this->success('成功');
    }
}